import axios from 'axios';
import { getApiBaseUrl } from '../config/api';

const instance = axios.create({
    baseURL: getApiBaseUrl(),
    timeout: 10000,
});

// 请求拦截器
instance.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem('token');
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        } else {
            // 如果 token 不存在，跳转到登录页面
            window.location.href = '/login';
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
instance.interceptors.response.use(
    (response) => {
        // 统一处理返回数据
        return response.data;
    },
    (error) => {
        // 统一处理错误
        return Promise.reject(error);
    }
);

export default instance;